package com.fenghuo.map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.fenghuo.model.MapPoint;
import com.fenghuo.myviews.MapView;
import com.fenghuo.utils.CustomToast;
import com.fenghuo.utils.Values;

import net.tsz.afinal.FinalDb;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class Ac_Main extends Activity implements OnClickListener, MapView.OnLayoutListener, MapView.OnClickPointListener {

    private MapView mapView = null;
    private Bitmap bitmap;//要显示的地图
    private int mapW, mapH;//地图图片的宽高
    private List<MapPoint> list;

    private LocationClient locationClient;//百度定位
    private boolean issearch = false;
    private boolean isshow = false;//提示次数
    public static final double lefttopLat = 39.078479;//纬度
    public static final double lefttopLot = 117.111617;//经度
    public static final double rightboLat = 39.065685;
    public static final double rightboLot = 117.124867;

    public static final double dy = lefttopLat - rightboLat;//跨越的
    public static final double dx = rightboLot - lefttopLot;
    public static final float bili = 29f / 15f;//1个像素多少米  [用来算半径]

    //左上角 longt:117.111617 lat:39.078479
    //右上角longt:117.12475  lat:39.078366
    //右下角longt:117.124867 lat:39.065685
    //左下角longt:117.111392  lat:39.065636
    private ImageView iv_menu;
    private ImageView iv_camare;
    private ImageView iv_location;
    private ImageView iv_note;
    private ImageView iv_search;
    private ImageView iv_location_top;
    private TextView tv_quitsearch;

    private String photopath;
    private String photoname;
    private FinalDb db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_main);
        mapView = (MapView) findViewById(R.id.myMapView);
        mapView.setOnLayoutListener(this);
        mapView.setOnClickPointListener(this);
        try {
            bitmap = BitmapFactory.decodeStream(getAssets().open("map_bg_road.jpg"));
            mapW = bitmap.getWidth();
            mapH = bitmap.getHeight();
            Values.mapH = mapH;
            Values.mapW = mapW;
        } catch (IOException e) {
            e.printStackTrace();
        }

        findviews();
        iv_camare.setOnClickListener(this);
        iv_location.setOnClickListener(this);
        iv_menu.setOnClickListener(this);
        iv_note.setOnClickListener(this);
        iv_search.setOnClickListener(this);
        iv_location_top.setOnClickListener(this);
        tv_quitsearch.setOnClickListener(this);
        db = FinalDb.create(Ac_Main.this, Values.DB_NAME);
        //=============定位
        locationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(8000);//设置发起定位请求的间隔时间为8000ms
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setNeedDeviceDirect(false);//返回的定位结果包含手机机头的方向
        option.setOpenGps(true);
        locationClient.setLocOption(option);
        locationClient.registerLocationListener(locationListener);
    }

    private void findviews() {
        iv_camare = (ImageView) findViewById(R.id.iv_camar_main);
        iv_location = (ImageView) findViewById(R.id.iv_location_main);
        iv_menu = (ImageView) findViewById(R.id.iv_menu_main);
        iv_note = (ImageView) findViewById(R.id.iv_note_main);
        iv_search = (ImageView) findViewById(R.id.iv_search_main);
        iv_location_top = (ImageView) findViewById(R.id.iv_location_top);
        tv_quitsearch = (TextView) findViewById(R.id.tv_quit_search);
    }

    private BDLocationListener locationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            switch (location.getLocType()) {
                case 61://gps定位结果
                case 161://表示网络/wifi定位结果
                case 68://网络连接失败时，查找本地离线定位时对应的返回结果
                    computLocation(location.getLatitude(), location.getLongitude(), location.getRadius());
                    break;
                case 62://扫描整合定位依据失败。此时定位结果无效。
                case 63://网络异常，没有成功向服务器发起请求。此时定位结果无效。
                    if (!isshow) {
                        showdialog();
                        isshow = true;
                    }
                    mapView.updatelocation(0, 0, false, 0);
                    break;
                default:
                    break;
            }
//			System.out.println("定位："+location.getLocType()+",lati:"+location.getLatitude()+",longti:"+location.getLongitude()+"::radius:"+location.getRadius());
        }


    };

    //左上角 longt:117.111617 lat:39.078479
    //右下角longt:117.124867 lat:39.065685

    private void computLocation(double latitude, double longtitude, float radus) {
        double xpersent1 = (longtitude - lefttopLot) / dx;
        double ypersent1 = 1 - (latitude - rightboLat) / dy;
        int mradius = (int) (radus / bili);
        if (mradius > 300) mradius = 150;
        int x = (int) (mapW * xpersent1) + 30;
        int y = (int) (mapH * ypersent1) + 130;
        mapView.updatelocation(x, y, true, mradius);
        Values.locationx = x;
        Values.locationy = y;
        if (xpersent1 > 1.5 || xpersent1 < -0.5 || ypersent1 > 1.5 || ypersent1 < -0.5) {
            Toast.makeText(Ac_Main.this, "主人，好像不在工业大学哦~~~", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Values.searchstrString.equals("")) {
            list = db.findAll(MapPoint.class);
            mapView.quitsearch(list);
        } else {
            String[] cons = Values.searchstrString.split(",");
            Values.searchstrString = "";
            String strwhere = "";
            for (int i = 0; i < cons.length; i++) {
                if (i == 0)
                    strwhere += (" kind like '%" + cons[i] + "%' or name like '%" + cons[i] + "%'");
                else
                    strwhere += (" or kind like '%" + cons[i] + "%' or name like '%" + cons[i] + "%'");
            }
            list = db.findAllByWhere(MapPoint.class, strwhere);
            if (list == null || list.size() < 1) {
                list = db.findAll(MapPoint.class);
                mapView.quitsearch(list);
                issearch = false;
                new CustomToast(Ac_Main.this).ShowMsg("未找到结果", CustomToast.Img_Info);
            } else {
                mapView.search(list);
                issearch = true;
                tv_quitsearch.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_menu_main:
                Intent intent = new Intent(Ac_Main.this, Ac_Choice.class);
                startActivity(intent);
                break;
            case R.id.iv_camar_main:
                if (checkSDCard()) {
                    Intent intent4 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent4.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photopath, "temp.jpg")));
                    startActivityForResult(intent4, 1);
                }
                break;
            case R.id.iv_location_main:
                Toast.makeText(Ac_Main.this, "正在定位...", Toast.LENGTH_SHORT).show();
                locationClient.start();
                break;
            case R.id.iv_note_main:
                Intent intent2 = new Intent(Ac_Main.this, Ac_Note.class);
                startActivity(intent2);
                break;
            case R.id.iv_search_main:
                Intent intent3 = new Intent(Ac_Main.this, Ac_Search.class);
                startActivity(intent3);
                break;
            case R.id.iv_location_top:
                mapView.updatelocation((int) (Math.random() * 600), (int) (Math.random() * 800), true, 0);
                break;
            case R.id.tv_quit_search:
                list = db.findAll(MapPoint.class);
                issearch = false;
                mapView.quitsearch(list);
                tv_quitsearch.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    int count = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && issearch) {
            list = db.findAll(MapPoint.class);
            mapView.quitsearch(list);
            issearch = false;
            tv_quitsearch.setVisibility(View.GONE);
            return true;
        } else {
            count++;
            if (count > 1) {
                finish();
            } else {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        count = 0;
                    }
                }).start();
                Toast.makeText(Ac_Main.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean checkSDCard() {
        boolean b = true;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) { // 判断是否存在SD卡
            String rootPath = Environment.getExternalStorageDirectory().getPath(); // 获取SD卡的根目录
            photopath = rootPath + Values.photo_Path;
            File file = new File(photopath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            b = false;
            new AlertDialog.Builder(this)
                    .setMessage("检测到手机没有存储卡！请插入手机存储卡再开启本应用。")
                    .setNegativeButton("确定", null).show();
        }
        return b;
    }

    @Override
    public void onlayout(int width, int height) {
        mapView.setBmp(bitmap, height, width);
        locationClient.start();
    }

    @Override
    protected void onDestroy() {
        if (bitmap != null && !bitmap.isRecycled())
            bitmap.recycle();
        locationClient.stop();
        super.onDestroy();
    }

    @Override
    public void oncklick(int id) {
        if (list.get(id).getName().equals("图书管")) {
            Intent intent = new Intent(Ac_Main.this, Ac_Instruction.class);
            startActivity(intent);
        }
        Toast.makeText(getApplicationContext(), "i：" + id, Toast.LENGTH_SHORT).show();
    }

    /**
     * 显示打开网络 /gps对话框
     */
    private void showdialog() {
        new AlertDialog.Builder(this)
                .setTitle("请打开网络/Gps以获取当前位置")
                .setMessage("无法定位")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
                    }
                }).setNegativeButton("取消", null).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0://定位 打开 gps
                    break;
                case 1://照相
                    File picture = new File(photopath, "temp.jpg");
                    startPhotoZoom(Uri.fromFile(picture));
                    break;
                case 2://裁剪
                    Values.currenturl = photoname;
                    Intent intent = new Intent(Ac_Main.this, Ac_Note.class);
                    startActivity(intent);
                    break;
                default:

                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 截切图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        photoname = System.currentTimeMillis() + ".jpg";
        File mypoto = new File(photopath, photoname);
        intent.putExtra("output", Uri.fromFile(mypoto));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputFormat", "JPEG");//返回格式
        intent.putExtra("outputX", 600);// 输出图片大小
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);//////////////[][][][重要]【新发现】
        startActivityForResult(intent, 2);
    }
}
